from server.db.session import with_session
from server.db.models.voice_clone_task_model import VoiceCloneTask

# 添加语音克隆任务到数据库
@with_session
def add_voice_clone_task_to_db(session, uid: str, timbre_id: str, url: str, task_id: str, task_status: str):
    task = VoiceCloneTask(uid=uid, timbre_id=timbre_id, url=url, task_id=task_id, task_status=task_status)
    session.add(task)
    session.commit()
    return task.task_id


# 根据任务ID从成功表中获取语音克隆任务
@with_session
def get_voice_clone_task_from_success_db_by_task_id(session, task_id: str):
    # return session.query(VoiceCloneTask).filter(VoiceCloneTask.task_id == task_id).first()
    result = session.query(VoiceCloneTask).filter(VoiceCloneTask.task_id == task_id).first()
    if result:
        return {
            "uid": result.uid,
            "timbre_id": result.timbre_id,
            "url": result.url,
            "task_id": result.task_id,
            "task_status": result.task_status
        }
    return None


# 根据音色ID获取语音克隆任务
@with_session
def get_voice_clone_task_by_timbre_id(session, timbre_id: str):
    result = session.query(VoiceCloneTask).filter(VoiceCloneTask.timbre_id == timbre_id).first()
    # ... existing code ...
    # 在返回前将对象转为字典
    if result:
        return {
            "id": result.id,
            "uid": result.uid,
            "timbre_id": result.timbre_id,
            "url": result.url,
            "task_id": result.task_id,
            "task_status": result.task_status,
            "created_at": result.created_at.isoformat() if result.created_at else None
        }
    return None



# 更新克隆任务成功表中的任务状态
@with_session
def update_voice_clone_task_status(session, task_id: str, task_status: str):
    result = session.query(VoiceCloneTask).filter(VoiceCloneTask.task_id == task_id).first() # 获取任务
    if result is not None:
        result.task_status = task_status # 更新任务状态
        session.add(result) # 添加到会话
        session.commit() # 提交会话
        return True
    return False



